<template>
  <div class="wrap">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card区域 -->
    <el-card class="box-card">
      <el-alert
        title="添加商品信息"
        type="info"
        show-icon
        center
        :closable="false"
      />

      <!-- 商品进度 (横向)-->
      <div class="steps_class">
        <!-- 这里的activeIndex 需要的是数字型 -->
        <el-steps :active="activeIndex * 1" align-center>
          <el-step title="基本信息" />
          <el-step title="商品参数" />
          <el-step title="商品属性" />
          <el-step title="商品图片" />
          <el-step title="商品内容" />
          <el-step title="完成" />
        </el-steps>
      </div>
      <!-- 商品进度条（纵向） -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="80px"
        label-position="top"
        :rules="addFormRules"
      >
        <!-- 这里的activeIndex 需要的是字符串型  -->
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="beforeLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name" />
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number" />
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number" />
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number" />
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateOptions"
                clearable
                @change="handleChange"
              />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane
            label="商品参数"
            name="1"
            style="max-height: 600px; overflow-y: auto"
          >
            <el-form-item
              v-for="item in paramsList"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(attr, index) in item.attr_vals"
                  :key="index"
                  :label="attr"
                  border
                  size="medium"
                />
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyList"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals[0]" />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              accept="image/*"
              :action="picUrl"
              :on-success="onSuccess"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              list-type="picture"
              :headers="headerO"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本 -->
            <quill-editor
              ref="myQuillEditor"
              v-model="addForm.goods_introduce"
            />
            <el-row style="margin-top: 15px">
              <el-col>
                <el-button type="primary" @click="add">添加商品</el-button>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <!-- 图片预览弹出框 -->
      <el-dialog
        :title="picPreview.name"
        :visible.sync="picDialogVisible"
        width="50%"
      >
        <div>
          <img :src="picPreview.url" class="urlImg">
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import _ from 'lodash';
import { getItem } from '@/utils/storage';
import {
  getCateListApi,
  getParamsApi,
  addGoodsApi
} from '@/api/add.js';
export default {
  name: 'Add',
  components: {},
  data() {
    return {
      content: '',
      picPreview: {}, // 图片预览
      picDialogVisible: false, // 图片预览是弹出框
      // 图片请求头
      headerO: {
        Authorization: getItem('token') && getItem('token')
      },
      // 图片请求路径
      picUrl:
        process.env.NODE_ENV === 'development'
          ? process.env.VUE_APP_API_PIC_URL
          : process.env.VUE_APP_API_PIC_URL,
      // 商品分类列表（级联选择器）
      cateList: [],
      // 商品分类配置项
      cateOptions: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 添加商品校验
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入价格名称', trigger: 'blur' },
          { min: 0, max: 5, message: '长度在1 到 5 个字符', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入重量名称', trigger: 'blur' },
          { min: 0, max: 5, message: '长度在 1到 5 个字符', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入数量名称', trigger: 'blur' },
          { min: 0, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入数量名称', trigger: 'blur' }
        ]
      },
      // 添加商品表单
      addForm: {
        goods_name: '',
        goods_price: '0',
        goods_weight: '0',
        goods_number: '0',
        goods_cat: [], // 商品分类
        pics: [], // 传给后端的图片的临时路径
        goods_introduce: '', // 商品介绍
        attrs: []// 属性参数（静态、动态）
      },
      activeIndex: '0',
      paramsList: [], // 参数列表数据(动态)
      onlyList: [], // 参数属性（静态）
      fileList: [] // 图片文件
    };
  },
  computed: {
    cateId() {
      return this.addForm.goods_cat.length !== 3
        ? ''
        : this.addForm.goods_cat[2];
    }
  },
  mounted() {
    this.getCateList();
  },
  methods: {
    // 添加商品
    add() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return this.$message.error('请填写必要的表单项！');
        //  动态参数
        this.paramsList.forEach((item) => {
          const body = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals ? item.attr_vals.join(',') : ''
          };
          this.addForm.attrs.push(body);
        });
        //  静态参数
        this.onlyList.forEach((item) => {
          const body = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals ? item.attr_vals.join(',') : ''
          };
          this.addForm.attrs.push(body);
        });

        const form = _.cloneDeep(this.addForm); // 深度克隆
        form.goods_cat = form.goods_cat.join(',');
        addGoodsApi(form).then((res) => {
          const { meta } = res.data;
          if (meta.status !== 201) return this.$message.error(meta.msg);
          this.$message.success(meta.msg);
          this.$router.push('/goods');
        });
      });
    },
    // 图片上传成功的回调
    onSuccess(response, file, fileList) {
      if (file.status === 'success') {
        const picU = {
          pic: file.response.data.tmp_path
        };
        this.addForm.pics.push(picU);
        this.$message.success('文件上传成功');
      }
    },
    // 删除图片的操作
    handleRemove(file, fileList) {
      this.addForm.pics.forEach((item, index) => {
        if (file.response.data.tmp_path === item.pic) {
          this.addForm.pics.splice(index, 1);
          this.$message.success('删除图片成功');
        }
      });
    },
    // 图片预览
    handlePreview(file) {
      file.name = file.name.split('.')[0];
      this.picPreview = file;
      this.picDialogVisible = true;
    },

    // 点击tab导航时触发
    tabClick(val) {
      // 商品参数
      if (val.index === '1' && this.cateId) {
        this.getParamsList('many');
      } else if (val.index === '2' && this.cateId) {
        this.getParamsList('only');
      }
    },
    // 获取参数列表
    getParamsList(value) {
      getParamsApi(this.cateId, { sel: value }).then((res) => {
        const { data, meta } = res.data;
        if (meta.status !== 200) return this.$message.error(meta.msg);
        data.forEach((item) => {
          item.attr_vals = item.attr_vals && item.attr_vals.split(',');
        });
        if (value === 'many') {
          this.paramsList = data;
        } else {
          this.onlyList = data;
        }
      });
    },
    // 监听级联切换
    beforeLeave(activeName) {
      if (activeName !== 0 && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类!');
        return false;
      }
    },
    // 级联选择器触发时
    handleChange() {
      const { goods_cat } = this.addForm;
      this.addForm.goods_cat = goods_cat.length !== 3 ? [] : goods_cat;
    },
    // 获取商品分类数据
    getCateList() {
      getCateListApi()
        .then((res) => {
          const { data, meta } = res.data;
          if (meta.status !== 200) return this.$message.error(meta.msg);
          this.cateList = data;
        })
        .catch((err) => {
          console.log(err);
        });
    }
  }
};
</script>
<style scoped lang='scss'>
.steps_class {
  margin: 15px 0;
}
.urlImg {
  width: 100%;
  height: 100%;
}
</style>
